package com.smart.service.poster;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.smart.common.entities.file.UploadBody;
import com.smart.common.entities.file.UploadResult;
import com.smart.common.exception.SmartException;
import com.smart.manager.member.entities.models.MemberProfileMain;
import com.smart.manager.pop.entities.assembler.PosterElement;
import com.smart.manager.pop.entities.models.PopBasicPoster;
import com.smart.manager.pop.entities.models.PopDisInviter;
import com.smart.manager.pop.entities.models.query.QPopBasicPoster;
import com.smart.service.FileService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * 海报生成服务
 *
 * @author Administrator
 */
@Service
@RequiredArgsConstructor
public class PosterService implements Serializable {

    private final FileService fileService;

    /**
     * @param posterId          海报地址
     * @param qrcodeText        二维码内容
     * @param memberProfileMain 会员信息
     * @return {@code String}
     */

    public String makePosterImage(Long posterId, String qrcodeText, MemberProfileMain memberProfileMain) {
        PopBasicPoster poster = new QPopBasicPoster().id.eq(posterId).setMaxRows(1).findOne();
        Assert.notNull(poster, "海报信息不存在");
        return makePosterImage(poster, qrcodeText, memberProfileMain.getNickName(), memberProfileMain.getAvatar()).getUrl();

    }

    public String makePosterImage(PopBasicPoster poster, String qrcodeText, MemberProfileMain memberProfileMain) {
        Assert.notNull(poster, "海报信息不存在");
        return makePosterImage(poster, qrcodeText, memberProfileMain.getNickName(), memberProfileMain.getAvatar()).getUrl();

    }
    /**
     * @param posterId          海报地址
     * @param qrcodeText        二维码内容
     * @param disInviter 代理信息
     * @return {@code String}
     */
    public UploadResult makePosterImage(Long posterId, String qrcodeText, PopDisInviter disInviter) {
        PopBasicPoster poster = new QPopBasicPoster().id.eq(posterId).setMaxRows(1).findOne();
        Assert.notNull(poster, "海报信息不存在");
        return makePosterImage(poster, qrcodeText, disInviter.getRealName(), disInviter.getAvatar());

    }


    /**
     * @param poster     海报对象
     * @param qrcodeText 二维码内容
     * @param nickName   昵称
     * @param avatarUrl  头像地址
     * @return {@code String}
     */
    public UploadResult makePosterImage(PopBasicPoster poster, String qrcodeText, String nickName, String avatarUrl) {
        try {
            //1.0 读原图
            InputStream httpImage = getHttpImage(poster.getHttpUrl());

            BufferedImage sourceImage;

            sourceImage = ImageIO.read(httpImage);


            //2.0 按照原图的宽 高 创建一个新画布 然后把原图填充进去
            BufferedImage huaBu = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics2D poster2D = huaBu.createGraphics();
            poster2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            poster2D.drawImage(sourceImage, 0, 0, null);


            List<PosterElement> elements = poster.getElements();

            for (PosterElement item : elements) {
                //填充头像 使用圆形填充
                if ("avatar".equals(item.getType()) && StrUtil.isNotBlank(avatarUrl)) {


                    InputStream headImage = getHttpImage(avatarUrl);
                    BufferedImage avatar = ImageIO.read(headImage);
                    BufferedImage newAvatar = new BufferedImage(item.getWidth(), item.getHeight(), BufferedImage.TYPE_INT_ARGB);
                    Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, avatar.getWidth(), avatar.getHeight());
                    Graphics2D avatar2D = newAvatar.createGraphics();
                    newAvatar = avatar2D.getDeviceConfiguration().createCompatibleImage(avatar.getWidth(), avatar.getHeight(), Transparency.TRANSLUCENT);
                    avatar2D = newAvatar.createGraphics();
                    avatar2D.setComposite(AlphaComposite.Clear);
                    avatar2D.fill(new Rectangle(newAvatar.getWidth(), newAvatar.getHeight()));
                    avatar2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
                    avatar2D.setClip(shape);
                    avatar2D.drawImage(avatar, 0, 0, null);
                    avatar2D.dispose();
                    //调整大小
                    BufferedImage outAvatar = resize(newAvatar, item.getWidth(), item.getHeight());
                    poster2D.drawImage(outAvatar, item.getMarginLeft(), item.getMarginTop(), null);


                }


                //填充二维码
                if ("qrcode".equals(item.getType())) {
                    QrConfig config = new QrConfig();
                    config.setWidth(item.getWidth());
                    config.setHeight(item.getHeight());
                    config.setBackColor(Color.white);
                    config.setMargin(0) ;
                    BufferedImage qrCode = QrCodeUtil.generate(qrcodeText, config);
                    poster2D.drawImage(qrCode, item.getMarginLeft(), item.getMarginTop(), null);
                }

                //设置昵称
                if ("nickname".equals(item.getType())) {
                    Font font = getFont(item.getFontsize());
                    poster2D.setFont( font);
                    poster2D.setColor(Color.decode(item.getFontcolor()));
                    poster2D.drawString(nickName, item.getMarginLeft(), item.getMarginTop());
                }

            }

            poster2D.dispose();
            huaBu.flush();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(huaBu, "jpg", outputStream);
            UploadBody.ByteFile byteFile = new UploadBody.ByteFile();
            byteFile.setData(outputStream.toByteArray()).setSince("poster").setContentType("image/jpg");
            return fileService.uploadFileByByte(byteFile, "poster", null);
        } catch (Exception e) {
            throw new SmartException("海报原图读取失败 无法识别的图片格式 建议使用PNG或者RGB模式的图片" + e.getMessage());
        }

    }


    public static InputStream getHttpImage(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return connection.getInputStream();
            }
        } catch (IOException e) {
            throw new RuntimeException("获取网络图片出现异常，图片路径为：" + url);
        }


        return null;
    }


    public static BufferedImage resize(BufferedImage img, int newW, int newH) {
        int w = img.getWidth();
        int h = img.getHeight();
        BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
        Graphics2D g = dimg.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
        g.dispose();
        return dimg;
    }


    public Font getFont(int fontSize) {
        try {
            return new Font("微软雅黑", Font.PLAIN, fontSize);
        } catch (Exception e) {
            return new Font(null, Font.PLAIN, fontSize);
        }

    }
}
